<template>
  <view class="container" @click="closeAllSwipeActions">
    <!-- 页面头部 -->
    <view class="header">
      <text class="header-title">
        {{ currentCategory ? `${currentCategory} 投资历史` : '投资历史' }}
      </text>
      <text v-if="currentCategory" class="back-button" @click="clearFilter">
        ← 返回全部
      </text>
    </view>
    
    <!-- 总计区域 -->
    <view class="summary-container">
      <view class="summary-stats">
        <view class="stat-item">
          <text class="stat-label">人民币投入</text>
          <text class="stat-value cny">{{ totalCny.toFixed(2) }} CNY</text>
        </view>
      </view>
    </view>
    
    <!-- 投资历史列表 -->
    <view class="list-container">
      <!-- 列表头部 -->
      <view class="list-header">
        <text class="col col-date">日期</text>
        <text class="col col-category">投资类别</text>
        <text class="col col-amount">金额 (CNY)</text>
      </view>
      
      <!-- 数据为空时的提示 -->
      <view v-if="filteredRecords.length === 0" class="empty-state">
        <text class="empty-icon">📊</text>
        <text class="empty-text">
          {{ currentCategory ? `暂无${currentCategory}投资记录` : '暂无投资记录' }}
        </text>
        <button class="empty-btn" @click="addRecord">添加记录</button>
      </view>
      
      <!-- 投资记录列表 -->
      <view v-for="(item, index) in filteredRecords" :key="index" class="swipe-action">
        <view class="list-item" @touchstart.stop="touchStart(index, $event)" @touchmove.stop="touchMove(index, $event)" @touchend.stop="touchEnd(index)" :style="{transform: `translateX(-${item.swipeWidth}px)`}" @click="viewRecordDetail(item)">
          <text class="col col-date">{{ formatDate(item.date) }}</text>
          <text class="col col-category">{{ getCategoryLabel(item.category) }}</text>
          <text class="col col-amount">{{ item.cny.toFixed(2) }}</text>
        </view>
        <view class="swipe-actions" :style="{width: item.swipeWidth + 'px'}">
          <view class="action-btn edit-btn" @click.stop="editRecord(index)">
            <text>编辑</text>
          </view>
          <view class="action-btn delete-btn" @click.stop="deleteRecord(index)">
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 添加记录悬浮按钮 -->
    <view class="add-button-container">
      <button class="add-button" @click="addRecord">+</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { onShow } from '@dcloudio/uni-app';
import { useRouter, useRoute } from "vue-router";
import { API_BASE_URL } from '../../utils/config';
import { baseGet, baseDel } from '../../utils/api';

const router = useRouter();
const route = useRoute();

// 投资记录数据
const records = ref([]);
const filteredRecords = ref([]);
const currentCategory = ref(''); // 当前筛选的投资类别

// 滑动相关状态
const startX = ref(0);
const currentIndex = ref(-1);
const ACTION_WIDTH = 160; // 操作按钮总宽度

// 计算总计
const totalCny = computed(() => {
  return filteredRecords.value.reduce((sum, item) => sum + item.cny, 0);
});

// 格式化日期显示
const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  const year = String(date.getFullYear()).slice(2); // 获取年份后两位
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}${month}${day}`;
};

// 获取投资类别标签
const getCategoryLabel = (category) => {
  const categoryMap = {
    '货币基金': '💰 货币基金',
    '定存': '🏦 定存',
    '基金': '📈 基金',
    '股票': '📊 股票'
  };
  return categoryMap[category] || category;
};

// 从后端API获取投资历史数据
const fetchRecords = async (category = '') => {
  try {
    const res = await baseGet('/investment-history');
    
    if (res.statusCode === 200 && res.data.success) {
      // 为每条记录添加swipeWidth属性
      records.value = res.data.data.map(item => ({
        ...item,
        swipeWidth: 0
      }));
      
      // 根据类别筛选数据
      if (category) {
        filteredRecords.value = records.value.filter(item => item.category === category);
        currentCategory.value = category;
      } else {
        filteredRecords.value = [...records.value];
        currentCategory.value = '';
      }
    } else {
      uni.showToast({
        title: res.data?.error || '获取数据失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取投资历史数据失败:', error);
    if (error.message !== '未登录') {
      uni.showToast({
        title: '网络错误，获取数据失败',
        icon: 'none'
      });
    }
  }
};

// 触摸开始事件
const touchStart = (index, e) => {
  // 关闭之前打开的滑动项
  if (currentIndex.value !== -1 && currentIndex.value !== index) {
    records.value[currentIndex.value].swipeWidth = 0;
  }
  startX.value = e.touches[0].clientX;
  currentIndex.value = index;
};

// 触摸移动事件
const touchMove = (index, e) => {
  if (index !== currentIndex.value) return;
  
  const currentX = e.touches[0].clientX;
  const diffX = startX.value - currentX;
  
  if (diffX > 0 && diffX <= ACTION_WIDTH) {
    records.value[index].swipeWidth = diffX;
  } else if (diffX > ACTION_WIDTH) {
    records.value[index].swipeWidth = ACTION_WIDTH;
  } else if (diffX < 0) {
    records.value[index].swipeWidth = 0;
  }
};

// 触摸结束事件
const touchEnd = (index) => {
  // 如果滑动距离超过一半，则完全展开，否则收起
  if (records.value[index].swipeWidth > ACTION_WIDTH / 2) {
    records.value[index].swipeWidth = ACTION_WIDTH;
  } else {
    records.value[index].swipeWidth = 0;
  }
};

// 关闭所有滑动项
const closeAllSwipeActions = () => {
  records.value.forEach(item => {
    item.swipeWidth = 0;
  });
  currentIndex.value = -1;
};

// 跳转到添加记录页面
const addRecord = () => {
  router.push('/pages/history/add');
};

// 编辑记录
const editRecord = (index) => {
  // 先关闭滑动项
  records.value[index].swipeWidth = 0;
  
  // 跳转到add页面并传递记录数据作为查询参数
  const record = records.value[index];
  router.push({
    path: '/pages/history/add',
    query: {
      mode: 'edit',
      id: record.id,
      date: record.date,
      cny: record.cny,
      category: record.category,
      usd: 0,
      exchange_rate: 0
    }
  });
};

// 清除筛选条件
const clearFilter = () => {
  currentCategory.value = '';
  filteredRecords.value = [...records.value];
  // 如果是从其他页面跳转过来的，清除URL参数
  if (route.query.category) {
    router.push({ path: '/pages/history/history' });
  }
};

// 查看记录详情
const viewRecordDetail = (record) => {
  // 先关闭所有滑动项
  closeAllSwipeActions();
  
  // 保存记录到本地存储，方便详情页获取
  uni.setStorageSync(`record_${record.id}`, JSON.stringify(record));
  
  // 跳转到详情页，使用replace而不是push，避免在页面栈中重复添加详情页
  // 这样无论查看多少条记录，返回时都会直接回到历史记录页面
  router.replace({
    path: '/pages/history/detail',
    query: {
      id: record.id,
      date: record.date,
      cny: record.cny,
      category: record.category,
      usd: record.usd || 0,
      exchange_rate: record.exchange_rate || 0,
      deposit_start_date: record.deposit_start_date || '',
      deposit_duration: record.deposit_duration || '',
      deposit_rate: record.deposit_rate || '',
      created_at: record.created_at || '',
      updated_at: record.updated_at || ''
    }
  });
};

// 删除记录
const deleteRecord = async (index) => {
  // 先关闭滑动项
  filteredRecords.value[index].swipeWidth = 0;
    
  const recordToDelete = filteredRecords.value[index];
    
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条投资记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          // 调用后端API删除记录
          const result = await baseDel(`/investment-history/${recordToDelete.id}`);
          
          if (result.statusCode === 200 && result.data.success) {
            // 更新本地数据
            filteredRecords.value.splice(index, 1);
            // 同时从原始数据中删除
            const originalIndex = records.value.findIndex(r => r.id === recordToDelete.id);
            if (originalIndex !== -1) {
              records.value.splice(originalIndex, 1);
            }
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: result.data?.error || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除记录失败:', error);
          if (error.message !== '未登录') {
            uni.showToast({
              title: '网络错误，删除失败',
              icon: 'none'
            });
          }
        }
      }
    }
  });
};

// 页面加载时获取数据
onMounted(() => {
  loadCategoryData();
});

// 页面显示时（包括从其他页面切回）获取数据
onShow(() => {
  loadCategoryData();
});

// 加载类别数据的通用函数
const loadCategoryData = () => {
  // 从localStorage中读取选中的类别
  const category = uni.getStorageSync('selectedCategory') || '';
  console.log('category', category);  
  // 清除存储的类别，避免下次进入时仍保持筛选
  if (category) {
    uni.removeStorageSync('selectedCategory');
    // 当从其他页面传入新的类别时，根据传入的类别获取数据
    fetchRecords(category);
  } else {
    // 没有新的类别参数传入时，根据当前筛选状态获取数据
    // 无论是否有筛选条件，都重新获取数据以确保显示最新记录
    fetchRecords(currentCategory.value || '');
  }
};
</script>

<style>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.container {
  padding: 0;
  background-color: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* 页面头部 */
.header {
  background-color: #3b82f6;
  padding: 0 16px;
  border-bottom: 1px solid #f0f0f0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  height: 56px;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: white;
  text-align: center;
  flex: 1;
}

.back-button {
  font-size: 16px;
  color: white;
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
}

/* 总计区域样式 */
.summary-container {
  background: #fff;
  margin: 16px;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.summary-stats {
  display: flex;
  justify-content: center;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  display: block;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
}

.stat-value.cny {
  color: #1989fa;
}

/* 列表容器样式 */
.list-container {
  margin: 16px;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

/* 列表头部 */
.list-header {
  display: flex;
  background-color: #f8f8f8;
  font-weight: bold;
  border-bottom: 1px solid #e0e0e0;
  padding: 16px;
  height: 56px;
  align-items: center;
}

/* 列表项样式 */
.swipe-action {
  position: relative;
  background-color: #fff;
  overflow: hidden;
}

.list-item {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: transform 0.3s ease;
  background-color: #fff;
  z-index: 1;
  position: relative;
}

.list-item:last-child {
  border-bottom: none;
}

/* 列样式 */
.col {
  display: flex;
  align-items: center;
  font-size: 14px;
  height: 100%;
}

.col-date {
  flex: 2;
  color: #333;
  text-align: left;
}

.col-category {
  flex: 3;
  color: #666;
  text-align: left;
}

.col-amount {
  flex: 2;
  color: #1989fa;
  font-weight: 500;
  justify-content: flex-end;
  text-align: right;
}

/* 空状态样式 */
.empty-state {
  padding: 60px 20px;
  text-align: center;
  background-color: #fff;
}

.empty-icon {
  font-size: 60px;
  display: block;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #999;
  display: block;
  margin-bottom: 24px;
}

.empty-btn {
  background-color: #1989fa;
  color: #fff;
  border: none;
  padding: 10px 24px;
  border-radius: 20px;
  font-size: 14px;
}

/* 滑动操作按钮 */
.swipe-actions {
  position: absolute;
  top: 0;
  right: 0;
  height: 100%;
  display: flex;
  z-index: 0;
}

.action-btn {
  width: 80px;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  color: #fff;
}

.edit-btn {
  background-color: #1989fa;
}

.delete-btn {
  background-color: #f56c6c;
}

/* 添加按钮样式 */
.add-button-container {
  position: fixed;
  bottom: 80px; /* 增加底部间距，避免被tabbar挡住 */
  right: 24px;
  z-index: 100;
}

.add-button {
  width: 56px;
  height: 56px;
  background-color: #1989fa;
  color: #fff;
  border: none;
  border-radius: 50%;
  font-size: 24px;
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.4);
  display: flex;
  justify-content: center;
  align-items: center;
}

.add-button:active {
  background-color: #096dd9;
  transform: scale(0.95);
}
</style>
